<!--
 * @Descripttion: 合同变更
 * @version: V1.0
 * @Author: GW
 * @Date: 2021-10-22 10:45:19
 * @LastEditors: GW
 * @LastEditTime: 2021-10-24 09:32:35
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <!-- <a-col class="btn-item" v-if="btnPermission('list')">
                    <div class="btns" @click="switchList('list')" v-if="showModel=='order'">
                        <a-icon class="btns-icon" type="unordered-list" />
                        <div class="btns-text">列表</div>
                    </div>
                    <div class="btns" @click="switchList('order')" v-else>
                        <a-icon class="btns-icon" type="container" />
                        <div class="btns-text">单据</div>
                    </div>
                </a-col> -->
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="switchList('list')" v-if="showModel=='order'">
                                <a-icon class="btns-icon" type="unordered-list" />
                                <div class="btns-text">列表</div>
                            </div>
                            <div class="btns" @click="switchList('order')" v-else>
                                <a-icon class="btns-icon" type="container" />
                                <div class="btns-text">单据</div>
                            </div>
                        </a-col>
                        <a-col :xs="btn_grid.xs" :sm="btn_grid.sm" :md="btn_grid.md" :lg="btn_grid.lg" :xl="btn_grid.xl">
                            <div class="btns" @click="submitServer">
                                <a-icon class="btns-icon" type="save" />
                                <div class="btns-text">保存</div>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>
            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">
                    {{voucherTitle}}
                </h3>
                <section v-show="showModel=='list'">
                    <!--列表-->
                    <dynamicList ref="dyList" :basePostData="basePostData" :sourceCode="sourceCode" @switchList="switchList" @dblclick="getIdByData" :reportCode="reportCodeList"></dynamicList>
                </section>
                <section v-show="showModel=='order'">
                    <!-- <div><span class="audit-status" v-show="voucherState==0">待审核</span><span class="audit-status" v-show="voucherState==1 || voucherState==10">{{voucherState==1?'已审核':'关闭'}}</span></div> -->
                    <a-form-model :layout="formLayout">
                        <div class="header-box">
                            <order-dynamic-form :FormData="orderHeaderData" @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <!-- <div class="edit-mask-header" v-show="editMask">
                                
                            </div> -->
                        </div>
                        <div class="table-box">
                            <a-tabs :activeKey="activeKeyContract" @change="callbackTabs">
                                <a-tab-pane :key="1" tab="合同标的">
                                    <div class="position-class">
                                        <a-table id="bills_tb" :columns="columns" :data-source="dataSource" :customRow="customClick" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChange" :size="small" bordered>
                                            <template v-if="isRouterAlive" slot="number" slot-scope="text, record, index">
                                                <div v-if="index == dataSource.length-1">
                                                    合计
                                                </div>
                                                <div v-else>
                                                    {{index+1}}
                                                </div>
                                            </template>
                                            <template v-for="col in slotArray" :slot="col" slot-scope="text, record,index">
                                                <div data-key="">
                                                    <editable-cell v-if="isRouterAlive" :checkType="checkType" :text="text" :col="col" :index="index" :record="record" :dataSource="dataSource" :unitsDataDetails="unitsDataDetails" :unitsAssistSelect="unitsAssistSelect" :dynamicAllData="dynamicFormData" :dynamicFormDataMap="dynamicFormDataMap"  @choiceAddData="choiceAddData(index,col,$event)" @change="onCellChange(index, col, $event)" @newAddData="handleAdd" />
                                                </div>
                                            </template>
                                        </a-table>
                                        <!-- <div class="edit-mask" v-show="editMask">
                                            
                                        </div> -->
                                    </div>
                                </a-tab-pane>
                                <a-tab-pane :key="2" tab="合同条款" force-render>
                                    <div class="position-class">
                                        <a-table id="bills_terms" :columns="columnsTerms" :data-source="dataSourceTerms" :customRow="customClickTerms" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChangeTerms" :size="small" bordered>
                                            <template v-for="col in slotArrayTerms" :slot="col" slot-scope="text, record,index">
                                                <div data-key="">
                                                    <editable-cell-min v-if="isRouterAliveTerms" :record="record" :index="index" :col="col" :text="text" @change="onCellChangeTerms(index, col, $event)" />
                                                </div>
                                            </template>
                                        </a-table>
                                        <!-- <div class="edit-mask" v-show="editMask">
                                            
                                        </div> -->
                                    </div>
                                </a-tab-pane>
                                <!-- <a-tab-pane :key="3" tab="收付信息">
                                    <div class="position-class">
                                        <a-table id="bills_payment" :columns="columnsPayment" :data-source="receivePaymentPlans" :customRow="customClickTerms" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChangeTerms" :size="small" bordered>
                                            <template v-for="col in slotArrayPayment" :slot="col" slot-scope="text, record,index">
                                                <div data-key="">
                                                    <editable-cell-min v-if="isRouterAliveTerms" :record="record" :index="index" :col="col" :text="text" @change="onCellChangeTerms(index, col, $event)" />
                                                </div>
                                            </template>
                                        </a-table>
                                        <div class="edit-mask" v-show="editMask">
                                            
                                        </div>
                                    </div>
                                </a-tab-pane> -->
                                <!-- <a-tab-pane :key="4" tab="附件">
                                    <div class="position-class">
                                        <a-table id="bills_payment" :columns="columnsFiles" :data-source="contractFiles" :customRow="customClickTerms" :scroll="{ x: 1000, y: 347 }" :pagination="false" @change="onTableChangeTerms" :size="small" bordered>
                                            <template v-for="col in slotArrayFiles" :slot="col" slot-scope="text, record,index">
                                                <div data-key="">
                                                    <editable-cell-min v-if="isRouterAliveTerms" :record="record" :index="index" :col="col" :text="text" @change="onCellChangeTerms(index, col, $event)" />
                                                </div>
                                            </template>
                                        </a-table>
                                        <div class="edit-mask" v-show="editMask">
                                            
                                        </div>
                                    </div>
                                </a-tab-pane> -->
                            </a-tabs>

                        </div>
                        <div class="footer-box">
                            <order-dynamic-form :FormData="orderFooterData"  @changetime="onChangeTime" @clickItem="setValue"></order-dynamic-form>
                            <div class="edit-mask-footer" v-show="editMask">
                                <!-- 遮罩（点击修改关闭遮罩） -->
                            </div>
                        </div>
                    </a-form-model>
                </section>
                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails ref="detailSearchRef" :reportCode="reportCodeDetail" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
                <section v-show="showModel=='statistical'">
                    <!--统计-->
                    <dynamicListDetails ref="statisticalSearchRef" :reportCode="reportCodeStatistical" :componentType="2" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
                <!--合同条款，收付信息，附件 的右键-->
                <ul v-show="visibleTerms" :style="{left:leftTerms+'px',top:topTerms+'px'}" class="contextmenu">
                    <li @click="handleAddTerms()">新增行</li>
                    <li @click="handleDeleteTerms()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>

            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder" :businessType="businessType"></drawerBox>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <div class="edit-mask" style="display:none">

        </div>
    </div>
</template>
<script>

import { save, examine, remove, getCode, getDetails, changeSave } from '@/api/contract/contractBills';
import editableCellMin from "@/views/production/workshop/editTable/EditableCell"
import pro from '@/mixins/procurement/pro';
export default {
    mixins: [pro],
    components: {
        editableCellMin,
    },
    data () {
        return {
            //基础 查询条件（列表 + 翻页）
            basePostData: {
                someBusinessType: null,    // 数据来源
            },
            sourceCode: 'Contract',
            reportCodeDetail: 'Contract_Detail_Report',            //明细code
            reportCodeStatistical: 'Contract_Statistic_Report',    //统计code
            reportCodeList: 'Contract_List_Report',                //列表code
            businessType: 2,               //选单时，非退货业务
            checkType: '',

            contractTypeId: null,//是否有合同类型 才能获取合同编码
            initDetails: true,   //初始只请求一次详情

            dataSourceNumberOther: 8,//初始多上行表格
            dataSourceTerms: [],        //合同条款数据
            receivePaymentPlans: [],    //收付信息数据
            contractFiles: [],          //附件信息数据
            visibleTerms: false,        //控制右键菜单显示
            topTerms: 0,
            leftTerms: 0,
            isRouterAliveTerms: true,   //用于刷新表格
            thisClickIdTerms: null,
            activeKeyOhter: null,//当前选择的标签页
            activeKeyContract: 1,
            customClickTerms: (record, index) => ({
                on: {
                    contextmenu: (e) => {//右键事件
                        e.preventDefault();
                        this.openMenuTerms(e);
                        console.log('右键点击的', index, e);
                        this.thisClickIdTerms = index;
                    },
                },
            }),
            //-------------------------------合同条款---------------------------
            columnsTerms: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    align: 'center',
                    width: 20,
                    customRender: (text, record, index) => {
                        return index + 1;
                    }
                },
                {
                    title: '条款编码',
                    dataIndex: 'code',
                    width: 100,
                    ellipsis: true,
                    scopedSlots: { customRender: 'codeTerms' },
                }, {
                    title: '条款名称',
                    dataIndex: 'name',
                    width: 140,
                    ellipsis: true,
                    scopedSlots: { customRender: 'nameTerms' },
                }, {
                    title: '条款内容',
                    dataIndex: 'content',
                    width: 140,
                    ellipsis: true,
                    // scopedSlots: { customRender: 'contentTerms' },
                }
            ],
            slotArrayTerms: ['codeTerms', 'nameTerms'],

            //-------------------------------收付信息---------------------------
            columnsPayment: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    align: 'center',
                    width: 20,
                    customRender: (text, record, index) => {
                        return index + 1;
                    }
                },
                {
                    title: '收付款日期',
                    dataIndex: 'planDate',
                    width: 100,
                    ellipsis: true,
                    scopedSlots: { customRender: 'planDate' },
                }, {
                    title: '收付款比例',
                    dataIndex: 'proportion',
                    width: 140,
                    ellipsis: true,
                    scopedSlots: { customRender: 'proportion' },
                }, {
                    title: '收付金额',
                    dataIndex: 'amount',
                    width: 140,
                    ellipsis: true,
                    scopedSlots: { customRender: 'amount' },
                }, {
                    title: '结算类型',
                    dataIndex: 'type',
                    width: 140,
                    ellipsis: true,
                    scopedSlots: { customRender: 'paymentType' },
                }
            ],
            slotArrayPayment: ['planDate', 'proportion', 'proportion', 'amount', 'paymentType'],
            //-------------------------------收付信息---------------------------
            columnsFiles: [
                {
                    title: '序号',
                    dataIndex: 'index',
                    align: 'center',
                    width: 20,
                    customRender: (text, record, index) => {
                        return index + 1;
                    }
                },
                {
                    title: '文件名称',
                    dataIndex: 'fileName',
                    width: 100,
                    ellipsis: true,
                    scopedSlots: { customRender: 'fileName' },
                }, {
                    title: '文件类型',
                    dataIndex: 'fileType',
                    width: 80,
                    ellipsis: true,
                }, {
                    title: '文件地址',
                    dataIndex: 'fileUrl',
                    width: 140,
                    ellipsis: true,
                    scopedSlots: { customRender: 'fileUrl' },
                },
            ],
            slotArrayFiles: ['fileName', 'fileUrl'],
            billsId: this.$route.query.id,
        };
    },
    created () {
        
    },
    activated () {
        this.billsId = this.$route.query.id;
        this.getIdByData(this.billsId);//获取变更的数据
    },
    watch: {
        visibleTerms (value) {
            if (value) {
                document.body.addEventListener("click", this.closeMenuTerms);
            } else {
                document.body.removeEventListener("click", this.closeMenuTerms);
            }
        },
    },
    methods: {
        //新增
        newForecast () {
            this.showModel = 'order';
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);

            this.initDetails = false;
            this.newOrderInitTable();//初始化 合同条款，收付信息，附件
        },
        //保存
        submit (requestData) {
            requestData.contractClauses = this.dataSourceTerms.filter(res => res.name != null);     //合同条款
            requestData.receivePaymentPlans = this.receivePaymentPlans.filter(res => res.amount != null);       //收付信息数据
            requestData.contractFiles = this.contractFiles.filter(res => res.fileName != null);     //附件信息数据
            changeSave(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    // if (!this.orderId) {
                    //     this.getIdByData(); //获取最新一条数据
                    // }
                    setTimeout(() => {
                        console.log('哈喽你好')
                        this.$store.commit("DELETE_TAB", this.$route.meta.id);
                        this.$router.push({ path: '/contract/contractBillsRecord' });
                    }, 500)

                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            remove(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            let requestData = {
                typeId: null
            };
            if (this.contractTypeId == null) {
                requestData = null;
                return false;
            } else {
                requestData.typeId = this.contractTypeId;
            }
            getCode(requestData).then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.receiptNumber = res.message;
                    console.log(this.orderHeaderData)
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'contractCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        // 选择 请购单
        choiceBillsFromPurchaseRequisition () {
            let postData = {
                sourceCode: 'PurchaseRequisition',      // 来源单
                title: '选请购单',
                businessType: 2, //1:退货业务 2：非退货业务 3: 退货 + 非退货 4: 发票
                someBusinessType: '0',    // 指定业务类型 默认 0
                startVoucherState: 0,
                endVoucherState: 10
            }
            this.$refs.searchList.onOpenBox(postData);
        },











        reloadTerms () {
            //刷新
            this.isRouterAliveTerms = false;
            this.$nextTick(function () {
                this.isRouterAliveTerms = true;
            });
        },
        //--------------------------------------右键-----------------------------
        openMenuTerms (e) {
            //显示右键菜单
            var x = e.pageX - 250;
            var y = e.pageY - 40;
            this.topTerms = y;
            this.leftTerms = x;
            this.visibleTerms = true;
        },
        closeMenuTerms () {
            //隐藏右键菜单
            this.visibleTerms = false;
        },
        handleAddTerms () {
            //新增数据
            let data = [];
            if (this.activeKeyOhter == 2) {
                //合同条款
                data = this.dataSourceTerms;
            } else if (this.activeKeyOhter == 3) {
                //收付信息
                data = this.receivePaymentPlans;
            } else if (this.activeKeyOhter == 4) {
                //附件
                data = this.contractFiles;
            }
            const newData = {
                number: data.length,
            };
            this.$nextTick(() => {
                data.splice(data.length, 0, newData);
                document.getElementById('documents-wrapper').scroll(0, this.$refs.print.scrollHeight);
                if (this.activeKeyOhter == 2) {
                    //合同条款
                    this.dataSourceTerms = data;
                } else if (this.activeKeyOhter == 3) {
                    //收付信息
                    this.receivePaymentPlans = data;
                } else if (this.activeKeyOhter == 4) {
                    //附件
                    this.contractFiles = data;
                }
                this.reloadTerms();
            })
        },
        handleDeleteTerms () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickIdTerms;
            let data = [];
            if (this.activeKeyOhter == 2) {
                //合同条款
                data = this.dataSourceTerms;
            } else if (this.activeKeyOhter == 3) {
                //收付信息
                data = this.receivePaymentPlans;
            } else if (this.activeKeyOhter == 4) {
                //附件
                data = this.contractFiles;
            }

            this.$confirm({
                title: "确认",
                content: (
                    <span>
                        您确定要{<span style="color:red;">删除</span>}该记录吗？
                    </span>
                ),
                onOk () {
                    let dataSource = [...data];
                    if (dataSource.length - 1 > _this.dataSourceNumberOther) {
                        //大于规定行数(删除)
                        data = dataSource.filter((item, index) => index !== numberId);
                    } else {
                        //小于规定行数(清空)
                        for (let i = 0; i < dataSource.length; i++) {
                            if (i === numberId) {
                                for (const key in dataSource[i]) {
                                    if (key != 'number') {
                                        dataSource[i][key] = null;
                                    }
                                }
                            }
                        }
                    }
                    if (_this.activeKeyOhter == 2) {
                        //合同条款
                        _this.dataSourceTerms = dataSource;
                    } else if (_this.activeKeyOhter == 3) {
                        //收付信息
                        _this.receivePaymentPlans = dataSource;
                    } else if (_this.activeKeyOhter == 4) {
                        //附件
                        _this.contractFiles = dataSource;
                    }
                    _this.reloadTerms();
                },
                onCancel () { },
            });
        },
        onCellChangeTerms (indexTable, dataIndex, value) {
            let data = [];
            if (this.activeKeyOhter == 2) {
                //合同条款
                data = this.dataSourceTerms;
            } else if (this.activeKeyOhter == 3) {
                //收付信息
                data = this.receivePaymentPlans;
            } else if (this.activeKeyOhter == 4) {
                //附件
                data = this.contractFiles;
            }

            const dataSource = [...data];
            const target = dataSource.find((item, index) => index === indexTable);
            console.log(target, dataIndex, value, indexTable);
            this.$set(target, dataIndex, value)
            if (dataIndex == 'codeTerms' || dataIndex == 'nameTerms') {
                //工序编码
                if (value) {
                    target['name'] = value.name;
                    target['code'] = value.code;
                    target['content'] = value.content;
                    target['remarks'] = value.remarks;
                } else {
                    target['name'] = null;
                    target['code'] = null;
                    target['content'] = null;
                    target['remarks'] = null;
                }
            } else if (dataIndex == 'paymentType') {
                //结算类型
                target['type'] = value;
            } else if (dataIndex == 'fileUrl') {
                //合同附件
                target['fileName'] = value.fileName;
                target['fileUrl'] = value.fileUrl;
                target['fileType'] = value.fileType;
            }
            this.$nextTick(() => {
                if (this.activeKeyOhter == 2) {
                    //合同条款
                    this.dataSourceTerms = dataSource;
                } else if (this.activeKeyOhter == 3) {
                    //收付信息
                    this.receivePaymentPlans = dataSource;
                } else if (this.activeKeyOhter == 4) {
                    //附件
                    this.contractFiles = dataSource;
                }
                this.reloadTerms();
            })
        },
        //--------------------------------------右键-----------------------------














        callbackTabs (key) {
            //标签页切换
            console.log(key);
            this.activeKeyContract = key;
            if (key >= 2) {
                this.activeKeyOhter = key;
            }
            //获取合同其他标签页的数据
            if (this.initDetails) {
                this.initDetails = false;
                getDetails({ id: this.orderId }).then(res => {
                    if (res.code === 200) {
                        //合同条款
                        this.dataSourceTerms = res.data.contractClauses;
                        //收付信息
                        this.receivePaymentPlans = res.data.receivePaymentPlans;
                        //附件信息
                        this.contractFiles = res.data.contractFiles;
                        if (this.dataSourceTerms.length < this.dataSourceNumberOther) {
                            //合同条款 补足表格
                            for (let i = this.dataSourceTerms.length; i < this.dataSourceNumberOther; i++) {
                                let array = {
                                    number: i + 1,
                                };
                                this.dataSourceTerms.push(array);
                            }
                            this.reloadTerms();
                        }
                        if (this.receivePaymentPlans.length < this.dataSourceNumberOther) {
                            //收付信息 补足表格
                            for (let i = this.receivePaymentPlans.length; i < this.dataSourceNumberOther; i++) {
                                let array = {
                                    number: i + 1,
                                };
                                this.receivePaymentPlans.push(array);
                            }
                            this.reloadTerms();
                        }
                        if (this.contractFiles.length < this.dataSourceNumberOther) {
                            //附件信息 补足表格
                            for (let i = this.contractFiles.length; i < this.dataSourceNumberOther; i++) {
                                let array = {
                                    number: i + 1,
                                };
                                this.contractFiles.push(array);
                            }
                            this.reloadTerms();
                        }
                    }
                })

            }
        },
        newOrderInitTable () {
            for (let i = this.dataSourceTerms.length; i < this.dataSourceNumberOther; i++) {
                let array = {
                    number: i + 1,
                };
                this.dataSourceTerms.push(array);
            }
            for (let i = this.receivePaymentPlans.length; i < this.dataSourceNumberOther; i++) {
                let array = {
                    number: i + 1,
                };
                this.receivePaymentPlans.push(array);
            }
            for (let i = this.contractFiles.length; i < this.dataSourceNumberOther; i++) {
                let array = {
                    number: i + 1,
                };
                this.contractFiles.push(array);
            }
            this.reloadTerms();
        }
    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .position-class {
        position: relative;
    }
</style>

